﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XQ.WeChatOfficialAccount.BLL.Common
{
    public class ClassHelper
    {
        /// <summary>
        /// 父类向子类拷贝
        /// </summary>
        /// <typeparam name="TParent"></typeparam>
        /// <typeparam name="TChild"></typeparam>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static TChild ParentCopyToChild<TParent, TChild>(TParent parent) where TChild : TParent, new()
        {
            TChild child = new TChild();
            var ParentType = typeof(TParent);
            var Properties = ParentType.GetProperties();
            foreach (var Propertie in Properties)
            {
                //循环遍历属性
                if (Propertie.CanRead && Propertie.CanWrite)
                {
                    //进行属性拷贝
                    Propertie.SetValue(child, Propertie.GetValue(parent, null), null);
                }
            }
            return child;
        }

        /// <summary>
        /// 子类向父类拷贝
        /// </summary>
        /// <typeparam name="TParent"></typeparam>
        /// <typeparam name="TChild"></typeparam>
        /// <param name="child"></param>
        /// <returns></returns>
        public static TParent ChildCopyToParent<TParent, TChild>(TChild child) where TChild : TParent, new() where TParent : new()
        {
            TParent parent = new TParent();
            var parentType = typeof(TParent);
            var Properties = parentType.GetProperties();
            foreach (var propertie in Properties)
            {
                //循环遍历属性
                if (propertie.CanRead && propertie.CanWrite)
                {
                    //进行属性拷贝
                    propertie.SetValue(parent, propertie.GetValue(child, null), null);
                }
            }
            return parent;
        }
    }
}
